package com.wl.zlmanage.controller;

import com.wl.zlmanage.bean.Kit;
import com.wl.zlmanage.bean.Notice;
import com.wl.zlmanage.bean.User;
import com.wl.zlmanage.constant.ActivityConstant;
import com.wl.zlmanage.mapper.KitMapper;
import com.wl.zlmanage.mapper.UserMapper;
import com.wl.zlmanage.utils.IOUtil;
import com.wl.zlmanage.utils.TimeUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * Created by wanglei on 2018/5/25.
 */
@Controller
public class FileController {

    private Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    UserMapper userDao;

    @Autowired
    KitMapper kitDao;

    @RequestMapping("/upload.do")
    @ResponseBody
    public Map upload(HttpSession session, HttpServletRequest request, Integer fileTypeId,
        Integer fileType,Integer qymark,Integer realSignId) {
        logger.info("fileTypeId:" + fileTypeId);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multipartRequest.getFileNames();
        Integer userId = (Integer) session.getAttribute("userId");
        List<Kit> kitList = null;
        try {
            String fileTypeDir = "";
            //签约客户附件
            if (fileType == 1) {
                fileTypeDir = ActivityConstant.UPLOAD_PATH_TYPE_SIGN_CUSTOM;
            } else if (fileType == 2) {
                fileTypeDir = ActivityConstant.UPLOAD_PATH_TYPE_APPLY;
            }else if(fileType == 3){
                fileTypeDir = ActivityConstant.UPLOAD_PATH_TYPE_SIGN_EXPEND;
            }else if(fileType == 4){
                fileTypeDir = ActivityConstant.UPLOAD_PATH_TYPE_EXPEND;
            }
            File fileDir = new File(
                ActivityConstant.UPLOAD_PATH + File.separator + fileTypeDir + File.separator
                    + String.valueOf(fileTypeId));
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            Kit kit = null;
            String suffix = null;
            String originalFilename = null;
            String saveFilename = null;
            while (iter.hasNext()) {
                MultipartFile file = multipartRequest.getFile(iter.next());
                originalFilename = file.getOriginalFilename();
                logger.info(file.getOriginalFilename());
                suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                int num = suffix.length();//得到后缀名长度
                saveFilename =
                    originalFilename.substring(0, originalFilename.length() - num - 1) + "_"
                        + System
                        .currentTimeMillis() + "." + suffix;
                saveFileFromInputStream(file.getInputStream(), fileDir.getAbsolutePath(),
                    saveFilename);
                kit = new Kit();
                kit.setFileType(fileType);
                kit.setFileTypeId(fileTypeId);
                kit.setFileName(file.getOriginalFilename());
                kit.setFilePath(fileDir.getAbsolutePath() + File.separator + saveFilename);
                kit.setUploadTime(TimeUtils.getCurrentDateString(TimeUtils.DATE_TIME_FORMAT));
                kit.setUploadUserId(userId);
                kitDao.saveKit(kit);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(null !=qymark && qymark == 1){
            List<Integer> getApplyIds = kitDao.getApplyIds(realSignId);
            kitList = kitDao.getApplyKitList(fileType, getApplyIds);
        }else {
            kitList = kitDao.getKitList(fileType, fileTypeId);
        }
//        File kitFile = null;
//        for (Kit kit : kitList) {
//            kitFile = new File(kit.getFilePath());
//            kit.setFileName(kitFile.getName());
//        }
        Map<String, Object> reMap = new HashMap<>();
        reMap.put("code", 200);
        reMap.put("data", kitList);
        return reMap;
    }

    @RequestMapping("/getKitList.do")
    @ResponseBody
    public List<Kit> getKitList(Integer fileTypeId, Integer fileType) {
        logger.info("fileTypeId:" + fileTypeId);
        List<Kit> kitList = kitDao.getKitList(fileType, fileTypeId);
//        File kitFile = null;
//        for (Kit kit : kitList) {
//            kitFile = new File(kit.getFilePath());
//            kit.setFileName(kitFile.getName());
//        }
        return kitList;
    }

    @RequestMapping("/getApplyKitList.do")
    @ResponseBody
    public List<Kit> getApplyKitList(Integer fileTypeId, Integer fileType, Integer signId) {
        logger.info("fileTypeId:" + fileTypeId);
        List<Integer> getApplyIds = kitDao.getApplyIds(signId);
        List<Kit> kitList = kitDao.getApplyKitList(fileType,getApplyIds);
//        File kitFile = null;
//        for (Kit kit : kitList) {
//            kitFile = new File(kit.getFilePath());
//            kit.setFileName(kitFile.getName());
//        }
        return kitList;
    }

    @RequestMapping("/deleteKit.do")
    @ResponseBody
    public String deleteKit(Integer id) {
        Kit kit = kitDao.getKitById(id);
        File kitFile = new File(kit.getFilePath());
        kitFile.delete();
        kitDao.deleteKit(id);
        return "success";
    }

    @RequestMapping("/showImage.do")
    public @ResponseBody
    void showImage(HttpServletResponse response, Integer id) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        Kit kit = kitDao.getKitById(id);
        String fullFileName = kit.getFilePath();
        FileInputStream fis = new FileInputStream(fullFileName);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }

    public void saveFileFromInputStream(InputStream stream, String path, String filename) {
        FileOutputStream fs = null;
        try {
            fs = new FileOutputStream(path + "/" + filename);
            byte[] buffer = new byte[1024 * 1024];
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = stream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
                fs.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(fs);
            IOUtil.close(stream);
        }
    }


    @RequestMapping("/uploadSystemFile.do")
    @ResponseBody
    public Map uploadSystemFile(HttpSession session, HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multipartRequest.getFileNames();
        Integer userId = (Integer) session.getAttribute("userId");
        List<Kit> kitList = null;
        try {
            String fileTypeDir = ActivityConstant.UPLOAD_PATH_TYPE_SYSTEM;

            File fileDir = new File(
                ActivityConstant.UPLOAD_PATH + File.separator + fileTypeDir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            Kit kit = null;
            String suffix = null;
            String originalFilename = null;
            String saveFilename = null;
            while (iter.hasNext()) {
                MultipartFile file = multipartRequest.getFile(iter.next());
                originalFilename = file.getOriginalFilename();
                logger.info(file.getOriginalFilename());
                suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                int num = suffix.length();//得到后缀名长度
                saveFilename =
                    originalFilename.substring(0, originalFilename.length() - num - 1) + "_"
                        + System
                        .currentTimeMillis() + "." + suffix;
                saveFileFromInputStream(file.getInputStream(), fileDir.getAbsolutePath(),
                    saveFilename);
                kit = new Kit();
                kit.setFileName(file.getOriginalFilename());
                kit.setFilePath(fileDir.getAbsolutePath() + File.separator + saveFilename);
                kit.setUploadTime(TimeUtils.getCurrentDateString(TimeUtils.DATE_TIME_FORMAT));
                kit.setUploadUserId(userId);
                kitDao.saveSysKit(kit);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> reMap = new HashMap<>();
        reMap.put("code", 200);
        reMap.put("data", kitList);
        return reMap;
    }

    @RequestMapping("/showSysImage.do")
    public @ResponseBody
    void showSysImage(HttpServletResponse response, Integer id) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        Kit kit = kitDao.getSysKitById(id);
        String fullFileName = kit.getFilePath();
        FileInputStream fis = new FileInputStream(fullFileName);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }

    @RequestMapping("/getSysKitList.do")
    @ResponseBody
    public List<Kit> getSysKitList(@RequestParam("page") int page,
        @RequestParam("limit") int limit) {
        int startIndex = (page - 1) * limit;
        List<Kit> reList = kitDao.getSysKitList(startIndex,limit);
        return reList;
    }

    @RequestMapping("/getSysKitListCount.do")
    @ResponseBody
    public Integer getSysKitListCount() {
        Integer count = kitDao.getSysKitListCount();
        return count;
    }

}
